package com.zrulin.findcomrade.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;

/**
 * @author zrulin
 * @create 2021-04-22 19:58
 */
public class JWTUtils {

    //签名
    private static final String SING = "@#TGL4654H@O$7978KTO^K$&^OLKMG";


    /**
     * 生成token      header.payload.sing
     */
    public static String getToken(String name,Integer id){
    //普通的写法
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7); //默认七天过期

        String token = JWT.create()
                .withClaim("username", name)
                .withClaim("username", id)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));

//        ****我第一次看的map写法
//        Calendar instance = Calendar.getInstance();
//        instance.add(Calendar.DATE,7); //默认七天过期
//        //创建 jwt builder
//        JWTCreator.Builder builder = JWT.create();
//        //payload
//        map.forEach((k,v)->{
//            builder.withClaim(k,v);
//        });
//        String token = builder.withExpiresAt(instance.getTime())
//                .sign(Algorithm.HMAC256(SING));
        return token;
    }

    /**
     * 验证token合法性
     * 要是错了就会直接报异常
     * 对了就可以返回DecoodedJwt对象来获取token中的值
     * @param token
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }


}
